import 'package:flutter/cupertino.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/home/home.dart';
import 'package:flutterproject/page/login_all/login/data/login_entity.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/util/sp_util/shared_preferences.dart';
import 'package:flutterproject/util/sp_util/sp_key.dart';
import 'package:get/get.dart';

class LoginController extends BaseController {
  HttpClient client = Get.find<HttpClient>();
  bool isCorrect = false;
  LoginEntity? loginEntity;

  TextEditingController phoneController = TextEditingController();
  TextEditingController pwdController = TextEditingController();

  final phoneFocusNode = FocusNode();
  final pwdFocusNode = FocusNode();

  void checkCorrect() {
    if (phoneController.text.length != 11) {
      isCorrect = false;
    }
    if (pwdController.text.isEmpty) {
      isCorrect = false;
    }
    if (phoneController.text.length == 11 && pwdController.text.isNotEmpty) {
      isCorrect = true;
    }
    update(["login"]);
  }

  Future<bool> login() async {
    if (!isCorrect) return false;
    if (phoneController.text.length != 11) {
      ToastUtil.showFailed("请输入手机号");
      return false;
    }
    if (pwdController.text.isEmpty) {
      ToastUtil.showFailed("请输入密码");
      return false;
    }
    try {
      DialogUtil.showLoading();
      loginEntity = await client.post<LoginEntity>(AddressManager.login, data: {
        "mobile": phoneController.text,
        "password": pwdController.text,
      });
      SPUtils().setLocalStorage(SPKey.mobile, phoneController.text);
      SPUtils().setLocalStorage(SPKey.token, loginEntity?.token ?? "");
      Get.off(HomePage());
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }
}
